package com.glela.order.service.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.glela.api.model.PayAppKeyInfo;
import com.glela.api.pay.alipay.component.Alipay;
import com.glela.api.pay.util.AlipayConfig;
import com.glela.api.pay.util.PayConfig;
import com.glela.api.pay.wechat.component.WeChat;
import com.glela.api.pay.yeepay.component.YeePay;
import com.glela.api.upload.qiniu.general.QiniuUtils;
import com.glela.common.constant.PayTypeEnum;
import com.glela.common.exception.PlatformException;
import com.glela.common.util.Config;
import com.glela.common.util.DateUtil;
import com.glela.common.util.HttpUtil;
import com.glela.common.util.ListUtils;
import com.glela.common.util.MD5;
import com.glela.common.util.OrderUtil;
import com.glela.common.util.StringUtil;
import com.glela.common.util.XmlUtil;
import com.glela.common.util.YeePayAESUtil;
import com.glela.common.util.YeePayDigest;
import com.glela.order.mapper.OrderObjectMapper;
import com.glela.order.mapper.OrderPayMapper;
import com.glela.order.model.GatewayPaymentModel;
import com.glela.order.model.OrderObject;
import com.glela.order.model.OrderPay;
import com.glela.order.service.OrderPayService;
import com.glela.order.service.OrderService;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.BaseRestrictions;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.service.BaseRestrictionsService;

@Service(value="orderPayService")
@Scope("singleton")
public class OrderPayServiceImpl implements OrderPayService {
	@Autowired
	private OrderPayMapper orderPayMapper;
	@Autowired
	private OrderObjectMapper orderObjectMapper;
	@Autowired
	private BaseRestrictionsService baseRestrictionsService;
	private static Logger logger = LoggerFactory.getLogger(OrderPayServiceImpl.class);
	@Autowired
	Alipay							alipay;
	@Resource(name = "orderService2")
	private OrderService			orderService2;

	@Override
	public Map<String, Object> saveWxPay(String orderObjectOrderSn, int payType, int totalFee, String ipAddress, String openId, WeChat weChat) throws IOException {
		// 新的支付单号
//		String paySn = "PAY" + OrderUtil.getOrderSn();
		String paySn =null;
		List<OrderPay> OrderPayList=
			orderPayMapper.selectByOrderSn(orderObjectOrderSn,payType);//微信支付 未支付
		Map<String, Object> weChaPay=null;
		if(ListUtils.isNotEmpty(OrderPayList)){
			OrderPay pay=OrderPayList.get(0);
			weChaPay=JSONObject.parseObject(pay.getPayUrl(), Map.class);
		}else{
		    paySn = "PAY" + OrderUtil.getOrderSn();
			PayAppKeyInfo payAppKeyInfo = orderService2.getPayAppKeyInfo(payType);
			weChaPay = weChat.weChaPay(payAppKeyInfo, orderObjectOrderSn, paySn, totalFee, ipAddress, openId);
			// 生成支付记录
			OrderPay orderpay = new OrderPay();
			orderpay.setOrderSn(orderObjectOrderSn);// 订单号
			orderpay.setPayType(payType);// 支付类型
			orderpay.setTotalFee(totalFee);// 支付金额（单位：分）
			orderpay.setPaySn(paySn);// 支付请求单号
			orderpay.setStatus(0);// 状态 0未支付
			orderpay.setIpAddress(ipAddress);// IP地址
			orderpay.setCreateTime(DateUtil.currentStringDate());// 创建时间
			orderpay.setExternalId(StringUtils.EMPTY);// 网关支付流水号
			orderpay.setPayUrl(JSON.toJSONString(weChaPay));// 网关支付链接
			int n = this.orderPayMapper.insertSelective(orderpay);
			// 支付记录插入失败
			if (n == 0) {
				throw new PlatformException(ErrorEnum.C21201, "保存支付记录失败");
			}
		}
		return weChaPay;
	}

	@Override
	public Map<String, String> saveAlipay(String orderObjectOrderSn, String ipAddress, int totalFee) throws UnsupportedEncodingException {
		// 新的支付单号
//		String paySn = "PAY" + OrderUtil.getOrderSn();
		String paySn =null;
		List<OrderPay> OrderPayList=
			orderPayMapper.selectByOrderSn(orderObjectOrderSn, PayTypeEnum.T2.getCode());//支付宝直连 未支付
		Map<String, String> orderStringMap=null;
		if(ListUtils.isNotEmpty(OrderPayList)){
			OrderPay pay=OrderPayList.get(0);
			orderStringMap=JSONObject.parseObject(pay.getPayUrl(), Map.class);
		}else{
		  paySn = "PAY" + OrderUtil.getOrderSn();
		  orderStringMap = alipay.getOrderString(orderService2.getAlipayAppKeyInfo(), orderObjectOrderSn, paySn, totalFee);
		  // 生成支付记录
		  OrderPay orderpay = new OrderPay();
		  orderpay.setOrderSn(orderObjectOrderSn);// 订单号
		  orderpay.setPayType(PayTypeEnum.T2.getCode());// 支付类型
		  orderpay.setTotalFee(totalFee);// 支付金额（单位：分）
		  orderpay.setPaySn(paySn);// 支付请求单号
		  orderpay.setStatus(0);// 状态 0未支付
		  orderpay.setIpAddress(ipAddress);// IP地址
		  orderpay.setCreateTime(DateUtil.currentStringDate());// 创建时间
		  orderpay.setExternalId(StringUtils.EMPTY);// 网关支付流水号
		  orderpay.setPayUrl(JSON.toJSONString(orderStringMap));// 网关支付链接
		  int n = this.orderPayMapper.insertSelective(orderpay);
		  // 支付记录插入失败
		  if (n == 0) {
			  throw new PlatformException(ErrorEnum.C21201, "保存支付记录失败");
		  }
		}
		return orderStringMap;
	}

	/**
	 * 调用网关支付
	 */
	@Override
	public ResponseEntity<?> goToSettleAccounts(Long userNo, String orderSn, int payType, String openId, String ipAddress) {
		// 校验支付订单是否存在
		OrderObject orderObject = this.orderObjectMapper.selectByOrderSn(orderSn);
		if (orderObject == null) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C21202), HttpStatus.OK);
		}
		if(orderObject.getOpenStore() == 1){
			if(payType != 22){
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20418), HttpStatus.OK);
			}
		}
		if (orderObject.getStatus() != 1) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C21213), HttpStatus.OK);
		}
		// 支付金额<单位：分>
		Integer totalFee = orderObject.getTotalFee();
		if (totalFee <= 0) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C41002), HttpStatus.OK);
		}
		// 请求网关支付接口链接
		String requestUrl = this.baseRestrictionsService.getBaseRestrictionsForCache("yeepay_url").getName();
		// 请求网关支付接口app_key
		String appKey = this.baseRestrictionsService.getBaseRestrictionsForCache("app_key").getName();
		// 网关支付成功回调Server链接
		String serverCallBackUrl = this.baseRestrictionsService.getBaseRestrictionsForCache("yeepay_callback_url").getName();
		// 网关支付成功回调Web链接
		String webCallBackUrl = this.baseRestrictionsService.getBaseRestrictionsForCache("yeepay_web_callback_url").getName();
		// 订单取消时间，支付有效时间和取消时间一样的话，可以保证在订单取消前，支付信息都是有效的
		int cancelOrderMinutes = this.baseRestrictionsService.getBaseRestrictionsForCache("cancel_order").getRestrictions();
		// 新的支付单号
		String paySn = "PAY" + OrderUtil.getOrderSn();
		// 查询是否存在成功支付的记录<所有支付方式>
		if (this.orderPayMapper.selectPaySuccessCountByOrderSn(orderSn) > 0) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C41001), HttpStatus.OK);
		}
		// 支付前校验易宝是否存在已支付的记录信息
//		List<OrderPay> orderPayAllList = orderPayMapper.selectAllByOrderSn(orderSn);
//		if (!CollectionUtils.isEmpty(orderPayAllList)) {
//			List<OrderPay> yeepayList = new LinkedList<>();
//			for(OrderPay orderPay : orderPayAllList){
//				switch (orderPay.getPayType()) {
//					case 20:
//					case 21:
//					case 22:
//					case 23:
//					case 24:
//						if ("SUCCESS".equals(this.queryYeePayOrderStatus(orderPay.getPaySn()))) {// 支付成功
//							return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C41001), HttpStatus.OK);
//						}
//						yeepayList.add(orderPay);
//						break;
//
//					default:
//						break;
//				}
//			}
//			orderPayAllList.clear();
//			orderPayAllList.addAll(yeepayList);
//		}
		// 查询是否存在支付记录<支付方式为payType>
		List<OrderPay> orderPayList = this.orderPayMapper.selectByOrderSn(orderSn, payType);
		if (CollectionUtils.isEmpty(orderPayList)) {

		} else {// 存在支付记录<1条或者多条>
			// 只处理第一条支付记录<已按创建时间倒序排序>
			OrderPay op = orderPayList.get(0);
			// 支付记录的有效期<单位：毫秒>
			long invalidTimeMillis = cancelOrderMinutes * 60 * 1000;
			// 上一次支付距离当前时间<单位：毫秒>
			long rangeTimeMillis = System.currentTimeMillis() - DateUtil.parse(op.getCreateTime(), "yyyy-MM-dd HH:mm:ss").getTime();
			// 支付记录已过期
			if (rangeTimeMillis > invalidTimeMillis) {
				// 将支付记录信息作废
//				this.orderPayMapper.invalidByPaySn(op.getPaySn(),DateUtil.getNow());
			} else {// 支付记录未过期
				//支付金额一致、非一键支付ONE_KEY,不用重新请求
				if (op.getTotalFee() == totalFee &&
						payType != PayTypeEnum.T23.getCode()) {
					Map<String, Object> result = new HashMap<String, Object>();
					result.put("payurl", op.getPayUrl());
					return new ResponseEntity<>(new ResponseResultModel<>(result), HttpStatus.OK);
				} else {// 支付金额不一致，支付记录失效
//					this.orderPayMapper.invalidByPaySn(op.getPaySn(),DateUtil.getNow());
				}
			}
			// 将当前的支付记录从orderPayList中删除，后面会判断剩下的支付记录中如果存在多条相同支付方式且待支付的支付记录，应该作废掉
//			orderPayList.remove(op);
//			if (orderPayList.size() > 1) {
//				for (OrderPay temoOP : orderPayList) {
//					// 将支付记录信息作废
//					this.orderPayMapper.invalidByPaySn(temoOP.getPaySn(),DateUtil.getNow());
//				}
//			}
		}
		JSONObject gpJson = new JSONObject();
		/** 此处调用网关支付接口 */
		try {
			// 将数字类型的支付方式转换为字母
			String converType = this.convertYeepayType(payType);
			if (StringUtil.isEmpty(converType)) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C41004), HttpStatus.OK);
			}
			GatewayPaymentModel gatewayPayment = new GatewayPaymentModel();
			gatewayPayment.setApp_key(appKey);
			gatewayPayment.setBussinessid(orderSn);
			gatewayPayment.setAmount(((double) orderObject.getTotalFee()) / 100);
			gatewayPayment.setAssure(0);
			gatewayPayment.setCallbackurl(serverCallBackUrl);
			gatewayPayment.setWebcallbackurl(webCallBackUrl);
			gatewayPayment.setIp(ipAddress);
			gatewayPayment.setOrderexpdate(cancelOrderMinutes);
			gatewayPayment.setRequestid(paySn);
			gatewayPayment.setPayproducttype(converType);
			gatewayPayment.setProductdesc(orderObject.getOrderSn());
			gatewayPayment.setProductname(orderObject.getOrderSn());
			if (payType == PayTypeEnum.T22.getCode()) {// 易宝公众号支付
				gatewayPayment.setPayproducttype("ONEKEY");
				gatewayPayment.setDirectcode("WAP_WECHATG");
				gatewayPayment.setUserno(openId);
				gatewayPayment.setAppid(Config.getString("wechat.appId"));
				gatewayPayment.setOpenid(openId);
			} else if (payType == PayTypeEnum.T23.getCode()) {// ONKEY支付
				gatewayPayment.setUserno(userNo + "");
			}
			gpJson = JSONObject.parseObject(HttpUtil.post(requestUrl, gatewayPayment.convertToMap()));
			if (gpJson.getJSONObject("error_response") != null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000, gpJson.getJSONObject("error_response").getString("msg")), HttpStatus.OK);
			}
			// 网关支付返回值为空，请求失败
			if (gpJson.getJSONObject("yeepay_trade_pay_response") == null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C41009), HttpStatus.OK);
			}
			// 网关支付流水号为空，请求失败
			if (StringUtil.isEmpty(gpJson.getJSONObject("yeepay_trade_pay_response").getString("externalid"))) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C41005), HttpStatus.OK);
			}
			// 支付URL为空，请求失败
			if (StringUtil.isEmpty(gpJson.getJSONObject("yeepay_trade_pay_response").getString("payurl"))) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C41003), HttpStatus.OK);
			}
			// 易宝微信扫码支付返回的支付链接为图片流，需要上传到七牛，转换为七牛的存储地址
			if (payType == PayTypeEnum.T24.getCode()) {

				BaseRestrictions baseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache("yeepay_h5_pay_page");
				if (baseRestrictions == null || StringUtils.isBlank(baseRestrictions.getName())) {
					logger.error("未配置扫码支付页面: yeepay_h5_pay_page,请检查  BaseRestrictions");
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
				}

				String qrpayurl = baseRestrictions.getName() + orderObject.getOrderSn();
				String qrUrl = QiniuUtils.getPayQrcode(qrpayurl, orderObject.getOrderSn());
				qrUrl = this.baseRestrictionsService.getBaseRestrictionsForCache("image_url").getName() + qrUrl;
				// 上传到七牛，将七牛返回的存储地址赋值给payurl
				//				gpJson.getJSONObject("yeepay_trade_pay_response").put("payurl",this.uploadQRCode(gpJson.getJSONObject("yeepay_trade_pay_response").getString("payurl"), orderObject.getOrderSn()));
				gpJson.getJSONObject("yeepay_trade_pay_response").put("payurl", qrUrl);

			}
			// 将网关支付链接保存到OrderObject表中
			this.orderObjectMapper.updateOrderObjectPayUrlById(orderObject.getId(), gpJson.getJSONObject("yeepay_trade_pay_response").getString("payurl"));
		} catch (Exception e) {
			logger.error("支付错误: --------->:", e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
		/*****************/
		// 生成支付记录
		OrderPay orderpay = new OrderPay();
		orderpay.setOrderSn(orderSn);// 订单号
		orderpay.setPayType(payType);// 支付类型
		orderpay.setTotalFee(totalFee);// 支付金额（单位：分）
		orderpay.setPaySn(paySn);// 支付请求单号
		orderpay.setStatus(0);// 状态 0未支付
		orderpay.setIpAddress(ipAddress);// IP地址
		orderpay.setCreateTime(DateUtil.currentStringDate());// 创建时间
		orderpay.setExternalId(gpJson.getJSONObject("yeepay_trade_pay_response").getString("externalid"));// 网关支付流水号
		orderpay.setPayUrl(gpJson.getJSONObject("yeepay_trade_pay_response").getString("payurl"));// 网关支付链接
		int n = this.orderPayMapper.insertSelective(orderpay);
		// 支付记录插入失败
		if (n == 0) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("payurl", gpJson.getJSONObject("yeepay_trade_pay_response").getString("payurl"));
		return new ResponseEntity<>(new ResponseResultModel<>(result), HttpStatus.OK);
	}

	/**
	* **********************************************
	* @Title: convertYeepayType 
	* @Description: 将数字类型的支付方式转换为字母 
	* @param @param payType
	* @param @return 
	* @return String
	* @throws	
	* @author NingChongQing	
	* @date 2017年8月31日 下午12:16:29 
	* **********************************************
	 */
	public String convertYeepayType(int payType){
		String convertType = "";
		if (payType == PayTypeEnum.T20.getCode()) {
			convertType = "WECHATAPP";
		} else if (payType == PayTypeEnum.T21.getCode()) {
			convertType = "ALIPAYAPP";
		} else if (payType == PayTypeEnum.T22.getCode()) {
			convertType = "WECHATG";
		} else if (payType == PayTypeEnum.T23.getCode()) {
			convertType = "ONEKEY";
		} else if (payType == PayTypeEnum.T24.getCode()) {
			convertType = "WECHATU";
		}
		return convertType;
	}
	
	/**
	* **********************************************
	* @Title: uploadQRCode 
	* @Description: 将图片上传至七牛服务器
	* @param @param hexImageString
	* @param @param orderSn
	* @param @return 
	* @return String
	* @throws	
	* @author NingChongQing	
	* @date 2017年8月31日 上午9:53:18 
	* **********************************************
	 */
	public String uploadQRCode(String hexImageString, String orderSn){// 扫码支付七牛服务器地址
		return this.baseRestrictionsService.getBaseRestrictionsForCache("image_url").getName() + QiniuUtils.uploadOrderQRCode("file/yeePay/", this.hex2byte(hexImageString), "jpg", orderSn);
	}
	
	/**
	* **********************************************
	* @Title: hex2byte 
	* @Description: 【十六进制流】转换为【二进制流】
	* @param @param s
	* @param @return 
	* @return byte[]
	* @throws	
	* @author NingChongQing	
	* @date 2017年8月31日 上午9:52:46 
	* **********************************************
	 */
	public byte[] hex2byte(String s) {
		byte[] src = s.toLowerCase().getBytes();
		byte[] ret = new byte[src.length / 2];
		for (int i = 0; i < src.length; i += 2) {
			byte hi = src[i];
			byte low = src[i + 1];
			hi = (byte) ((hi >= 'a' && hi <= 'f') ? 0x0a + (hi - 'a') : hi - '0');
			low = (byte) ((low >= 'a' && low <= 'f') ? 0x0a + (low - 'a') : low - '0');
			ret[i / 2] = (byte) (hi << 4 | low);
		}
		return ret;
	}
	
	/**
	 * 更新支付记录状态<生效>
	 */
	@Override
	public int modifyPaymentSuccess(String paySn,String currTime) {
		return this.orderPayMapper.effectByPaySn(paySn,currTime);
	}
	
	/**
	 * 根据支付单号查询支付记录
	 */
	@Override
	public OrderPay selectByPaySn(String paySn) {
		return this.orderPayMapper.selectByPaySn(paySn);
	}
	
	/**
	 * 根据易宝交易流水号查询支付记录
	 */
	@Override
	public OrderPay selectByExternalId(String externalId) {
		return this.orderPayMapper.selectByExternalId(externalId);
	}
	
	/**
	 * 查询是否存在已成功支付的记录
	 */
	@Override
	public int selectPaySuccessCountByOrderSn(String orderSn) {
		return this.orderPayMapper.selectPaySuccessCountByOrderSn(orderSn);
	}

	@Override
	public List<OrderPay> selectSuccess(String orderSn) {
		return orderPayMapper.selectPaySuccessByOBJOrderSn(orderSn);
	}
	
	@Override
	public List<OrderPay> selectAllByOrderSn(String orderSn) {
		return orderPayMapper.selectAllByOrderSn(orderSn);
	}
	
	/**
	* **********************************************
	* @Title: queryYeePayOrderStatus 
	* @Description: 根据PaySn查询易宝接口，判断支付记录是否成功支付
	* @param requestid 商户订单号
	* @param @return 
	* @return String
	* @throws	
	* @author NingChongQing	
	* @date 2017年10月16日 下午2:06:51 
	* **********************************************
	 */
	@Override
	public String queryYeePayOrderStatus(String requestid) {
		String status = "FAIL";
		try {
			String keyForAes = YeePay.SECRET_KEY.substring(0, 16);// 密文
			String customernumber = YeePay.CUSTOMER_NUMBER;// 商户编号
			String[] stringArray = { customernumber, requestid};
			// 签名完成
			String hmac = YeePayDigest.getHmac(stringArray, YeePay.SECRET_KEY);
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("customernumber", customernumber);// 商户编号
			paramMap.put("requestid", requestid);//商户订单号
			paramMap.put("hmac", hmac);//商户订单号
			String url = "https://o2o.yeepay.com/zgt-api/api/queryOrder";
			String data = YeePayAESUtil.encrypt(JSONObject.toJSONString(paramMap), keyForAes);
			String content = "customernumber=" + customernumber + "&data=" + data;
			String result = YeePayAESUtil.decrypt(JSONObject.parseObject(HttpUtil.doPost(content, url, "application/x-www-form-urlencoded")).get("data").toString(), keyForAes);
			// INIT：未支付，SUCCESS：已支付，FAIL：支付失败，SETTLECONFIRM：担保交易确认，仅担保交易时存在该状态
			if(!StringUtil.isEmpty(result)&&
					JSONObject.parseObject(result) != null&&
					!StringUtil.isEmpty(JSONObject.parseObject(result).getString("status"))){
				status = JSONObject.parseObject(result).getString("status");
			}
		} catch (Exception e) {
			status ="RESTART";
			logger.error("查询易宝支付状态错误: --------->:" ,e.getMessage(),e);
		}
		return status;
	}
	
	/**
	* **********************************************
	* @Title: queryAliPayOrderStatus 
	* @Description: 根据PaySn查询支付宝接口，判断支付记录是否成功支付
	* @param requestid 商户订单号
	* @param @return 
	* @return String
	* @throws	
	* @author NingChongQing	
	* @date 2017年10月16日 下午2:06:51 
	* **********************************************
	 */
	@Override
	public String queryAliPayOrderStatus(String requestid) {
		String status = "TRADE_FAIL";
		try {
			AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.url,AlipayConfig.appId,AlipayConfig.appPrivateKey0,"json","utf-8",AlipayConfig.alipayPublicKey0);
			AlipayTradeQueryModel model = new AlipayTradeQueryModel();
			model.setOutTradeNo(requestid);
			AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
			request.setBizModel(model);
			AlipayTradeQueryResponse response = alipayClient.execute(request);
			if (response != null && !StringUtil.isEmpty(response.getTradeStatus())) {
				status = response.getTradeStatus();
			}
			// 交易状态： WAIT_BUYER_PAY（交易创建，等待买家付款）、TRADE_CLOSED（未付款交易超时关闭，或支付完成后全额退款）、TRADE_SUCCESS（交易支付成功）、TRADE_FINISHED（交易结束，不可退款）
		} catch (Exception e) {
			logger.error("查询支付宝支付状态错误: --------->:" ,e.getMessage(),e);
		}
		return status;
	}
	
	/**
	* **********************************************
	* @Title: queryWechatPayOrderStatus 
	* @Description: 根据PaySn查询微信接口，判断支付记录是否成功支付
	* @param requestid 商户订单号
	* @param @return 
	* @return String
	* @throws	
	* @author NingChongQing	
	* @date 2017年10月16日 下午2:06:51 
	* **********************************************
	 */
	@Override
	public String queryWechatPayOrderStatus(String requestid) {
		String status = "FAIL";
		try {
			Map<String, String> map = new HashMap<String, String>();
			map.put("appid", PayConfig.appId0);
			map.put("mch_id", PayConfig.partnerId0);
			map.put("out_trade_no", requestid); 
			map.put("nonce_str", "Jj6AOA9a9GY0yhJf4FfROsYHL3exUCMv"); 
			//获得签名
			StringBuilder sign = new StringBuilder();
			sign.append(createSign(map)).append("&key=").append("Jj6AOA9a9GY0yhJf4FfROsYHL3exUCMv");
			String signstr = MD5.md5(sign.toString()).toUpperCase();
			String xml = createXML(map, signstr);
			String url = "https://api.mch.weixin.qq.com/pay/orderquery";
			String contentType = "text/xml";
			String outxml = HttpUtil.doPost(xml, url, contentType);
			if (!StringUtil.isEmpty(outxml)) {
				Map<String, Object> outmap = XmlUtil.getMapByXml(outxml);
				if (outmap != null && "SUCCESS".equals(outmap.get("return_code").toString().toUpperCase())) {
					// SUCCESS—支付成功;REFUND—转入退款;NOTPAY—未支付;CLOSED—已关闭;REVOKED—已撤销（刷卡支付）;USERPAYING--用户支付中;PAYERROR--支付失败(其他原因，如银行返回失败)
					if (outmap.get("trade_state") != null) {
						status = outmap.get("trade_state").toString().toUpperCase();
					}
				}
			}
		} catch (Exception e) {
			logger.error("查询微信支付状态错误: --------->:" ,e.getMessage(),e);
		}
		return status;
	}
	
	private String createSign(Map<String, String> params) throws UnsupportedEncodingException {
        Set<String> keysSet = params.keySet();
        //微信要求 参数名ASCII字典序排序
        Object[] keys = keysSet.toArray();
        Arrays.sort(keys);
        StringBuffer temp = new StringBuffer();
        boolean first = true;
        for (Object key : keys) {
            if (first) {
                first = false;
            } else {
                temp.append("&");
            }
            temp.append(key).append("=");
            Object value = params.get(key);
            String valueString = "";
            if (null != value) {
                valueString = value.toString();
            }
            temp.append(valueString);
            //temp.append(URLEncoder.encode(valueString, "UTF-8"));
        }
        return temp.toString();
    }
	
	private String createXML(Map<String, String> params, String sign) throws UnsupportedEncodingException {
	        Set<String> keysSet = params.keySet();
	        //微信要求 参数名ASCII字典序排序
		Object[] keys = keysSet.toArray();
		Arrays.sort(keys);
		StringBuffer temp = new StringBuffer();
		temp.append("<xml>") ;
		for (Object key : keys) {
		    temp.append("<").append(key).append(">");
		    Object value = params.get(key);
		    String valueString = "";
		    if (null != value) {
		        valueString = value.toString();
		    }
		    temp.append(valueString);
		    temp.append("</").append(key).append(">");
		}
		
		temp.append("<sign>").append(sign).append("</sign>").append("</xml>") ;
	    return temp.toString();
	}

	@Override
	public boolean modifOk(int id, String payId, String payTime) {
		return orderPayMapper.updateStatusOkById(id, payId, payTime) == 1;
	}
	
}
